package com.test.lock;

/**
 * @author ：biws
 * @date ：Created in 2020/12/18 22:29
 * @description：
 */
public class Semaphore extends Object {
    private int count;

    public Semaphore(int startingCount){
        count = startingCount;
    }

    public void down(){
        synchronized (this) {
            while (count <= 0) {
                // We must wait
                try {
                    wait();
                } catch (InterruptedException ex) {
                    // I was interupted, continue onwards
                }
            }

            // We can decrement the count
            count--;
        }

    }

    public void up(){
        synchronized (this) {
            count++;
            //notify a waiting thread to wakeup
            if (count == 1 ) {
                notify();
            }
        }
    }
}
